/*************************************************
 *FileName:      recharge.js
 *Description:   充值.js
 *Others:        陈灿
 *************************************************/
    /*
     * 启动
     */
    mui.init();
    mui('.mui-scroll-wrapper').scroll({
        indicators: false,      //是否显示滚动条 默认为true
        deceleration: 0.003,    //阻尼系数,系数越小滑动越灵敏 默认0.0006
        bounce: true           //是否启用回弹 默认true
    });
    mui.init({
        beforeback: function() {
            var list = plus.webview.currentWebview().opener();//触发父页面的自定义事件(refresh),从而进行刷新
            mui.fire(list, 'notecase');//返回true,继续页面关闭逻辑
            return true;
        }
    })
    /*
     * 变量初始化
     */
    var uid = localStorage.replace_uid;
    var token = localStorage.replace_token;
    var system, sub, money,type,moneys;
    // plus.webview.currentWebview().setStyle({
    //     softinputMode: "adjustResize"  // 弹出软键盘时自动改变webview的高度
    // });
    /*
     * 主程序
     */ 
    $(document).ready(function() 
    {
        //样式加载
        pagecss();
    });
    /**
     * pagecss
     * 样式加载
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function pagecss(){
        mui.plusReady(alode)
        $('.recharge .payment a').on('tap',function(){//单选，选择支付方式
            $(this).addClass('active').siblings().removeClass('active');
            judge();
        })
        
        $('.recharge .content .price').on('tap',function(){//单选，选择支付方式
            $(this).addClass('pitch').siblings('.price').removeClass('pitch');
            judge();
        })
         $('.import').on('input',function(){//赋值给总计
            oSpan=$(this).val();
            $(this).siblings('.color-span').text(oSpan*sub);
            judge();
        })   
        
        $('.rdntn.color').on('tap',function(){
            
        })
    }
    function judge(){
        money = $('.pitch').find('em').length>0? $('.pitch').find('.right-a').text() :$('.pitch').find('.import').val();
        type =$('.payment .active').attr('id');
        $('.rdntn')[ money&&type ? 'addClass':'removeClass']('color');  
        if($('.pitch').find('.import').length>0){
            moneys=oSpan;
        }else{
            moneys =$('.pitch .right-a span').text();
        }
    }//判断是否全写
    /**
     * adds //方法名
     * @陈灿 //作者名
     * @DateTime 2018-01-010T0116:25:00+0800 //时间
     * @param    int    $goods_id //参数
     * @param    array  $data //参数
     * @return    array  [error_code, error_msg, goods_id] //返回值
     */

    var pay = 0;
    var amount = 0;
    var uid = localStorage.replace_uid;
    var channel=null;
    var apayChannel = null;
    var wechatChannel = null;
    var ALIPAYSERVER = DOMAIN_NAME + '/index.php/api/Alinotify/ali'
    var WXPAYSERVER = DOMAIN_NAME+'/wechat/index.php?payid=wxpay';

    // function plusReady(){
        // 获取支付通道
        document.addEventListener("plusready", function () {
            // 扩展API加载完毕，现在可以正常调用扩展API
            plus.payment.getChannels(function (s) {
                channels = s;
                for (var i in channels) {
                    var channel = channels[i];
                    if (channel.id == 'alipay') {
                        apayChannel = channel;
                    } else if (channel.id == 'wxpay') {
                        wechatChannel = channel;
                    }
                }
            }, function (e) {
                mui.alert("获取支付通道列表失败：" + e.message,'提示','确定',function(){},'div');
            });
        }, false);
    // }
    // document.addEventListener('plusready',plusReady,false);

    
    //支付宝充值
    function aliPayRequest(){
        mui.post(ALIPAYSERVER, {
            amount: moneys, task_id: localStorage.replace_token, uid: localStorage.replace_uid,abc: 123,type:'recharge',pay:pay,mobile_ststem:system
        }, function (data) {
            plus.nativeUI.closeWaiting();
            if(data){
                plus.payment.request(apayChannel, data, function (result) {
                    plus.nativeUI.alert("支付宝支付成功",function(){
                        console.log(JSON.stringify(result));
                        mui.back();
                    },"支付宝");
                    console.log(result);
                }, function (e) {
                    console.log(JSON.stringify(e));
                });
            } else {
                mui.alert("支付宝付费失败");
            }
        });
    }

    function wxPayRequest(){
        var url=WXPAYSERVER;
        var appid=plus.runtime.appid;
        url+='&appid='+appid+'&task_id='+localStorage.replace_token+'&uid='+localStorage.replace_uid+'&total='+moneys+'&type=recharge&amount='+pay+'&mobile_system='+system;
        w=plus.nativeUI.showWaiting();
        // 请求支付订单
        var xhr=new XMLHttpRequest(); 
        xhr.onreadystatechange=function(){ 
            switch(xhr.readyState){
                case 4: 
                    w.close();w=null;
                    if(xhr.status==200){
                        var order=xhr.responseText;
                        plus.payment.request(wechatChannel,order,function(result){
                            plus.nativeUI.alert("微信支付成功",function(){
                                mui.back();
                            },"微信");
                        },function(e){
                            if(e.code == '-100'){
                                plus.nativeUI.alert("已放弃微信支付");
                            }else{
                                plus.nativeUI.alert("微信支付失败："+e.code);
                            }
                        });
                    }else{
                        plus.nativeUI.alert("获取订单信息失败！",null,"微信");
                    }
                    break;
                default:
                    break;
            }
        };
        xhr.open('GET',url);
        xhr.send();
    }
    /**
     * alode
     * 充值比列
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function alode(){
        var phonsyt =common.browserType();
        if(phonsyt.android){
            system='android';
        }else{
            system='ios';
        }
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/user/rechargeRate",
            dataType:'jsonp',
            data: { uid: uid, token: token, system:system},
            success: function(data) {
                if(data.error_code == 0){
                    sub = parseFloat(data.data);
                    $('.price').each(function(){
                        var mysub = parseFloat($(this).find('.color-span').text());
                        var value=Math.round(parseFloat(mysub/sub)*100)/100;
                        var xsd=value.toString().split(".");
                        var money=  xsd.length==1 ? value.toString()+".00": (xsd.length>1)&&(xsd[1].length<2) ? value.toString()+"0" : value;
                        $(this).find('.right-a span').text(money);
                    })
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    mui.toast(data.error_msg,{ duration:2000, type:'div' });
                }
            }
        }); 
    }

    $('.rdntn').on('tap',function(){
        var method = '';
        pay = $('.box .pitch .color-span').html();
        amount= $('.box .pitch .right-a span').html();
        var url = WXPAYSERVER + '&task_id='+localStorage.replace_token+'&uid='+localStorage.replace_uid+'&total='+pay+'&type=recharge&amount=0.01&mobile_ststem='+system;
        if($('.payment .active').hasClass('alipay')){
            aliPayRequest();
        }else if($('.payment .active').hasClass('wechat')){
            wxPayRequest();
        }else{
        }
        
    });
